<template>
  <a-select v-model="value" placeholder="请选择" allowClear @change="onChange">
    <a-select-option v-for="item in dictData" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
  </a-select>
</template>

<script>
import { getDict } from "@/services/system/api"
export default {
  name: 'DictSelect',
  props: {
    params: {
      type: Object,
      default: () => {},
      required: false
    },
    renderOpts: {
      type: Object,
      default: () => {},
      required: false
    }
  },
  data () {
    return {
      row: undefined,
      column: undefined,
      dictData: {},
      value: undefined,
      label: undefined
    }
  },
  watch: {
    params () {
      this.load()
    }
  },
  created () {
    if (this.renderOpts.props.dictField) {
      const params = {}
      params.dictField = this.renderOpts.props.dictField
      this.$http.post(getDict,params).then(res => {
        this.dictData = res.result
      })
    }
    this.load()
  },
  methods: {
    load () {
      if (this.renderOpts.options) {
        this.dictData = this.renderOpts.options
      }
      const { row, column } = this.params
      this.row = row
      this.column = column
      let key = column.property.replace('Name', undefined)
      if (!key) {
        key = column.property
      }
      if (row[key]) {
        this.value = row[key]
      } else {
        if (row[column.property]) {
          this.value = row[column.property]
        }
      }
    },
    onChange (value) {
      // this.label = option.label
      if (value) {
        this.dictData.forEach((item) => {
        if (item.dictKey === value) {
          this.label = item.dictValue
          return undefined
        }
      })
      } else {
        this.label = undefined
      }
      const { row, column } = this
      const key = column.property.replace('Name', '')
      row[column.property] = this.label
      row[key] = value
      if (this.renderOpts.events) {
        if (this.renderOpts.events.change) {
          this.renderOpts.events.change(value, row)
        }
      }
    }
  }
}
</script>
